package upload

import (
	"fmt"
	"io"
	"os"
	"strings"
)

// @auth Crastlin@163.com
// @date 2020-10
// @update 2022-08

type Local struct {
	Driver
}

// InitLocal init local driver
func InitLocal(opt *Option, domain string) Uploader {
	local := &Local{Driver{Config: opt, Domain: domain}}
	return local
}

// CheckPath check root path
func (l *Local) CheckPath(autoCreate bool, path ...string) bool {
	if len(path) > 0 && path[0] != "" {
		l.fullPath = path[0]
	} else {
		l.fullPath, _ = l.GetSavePathInfo()
	}
	if _, err := os.Stat(l.fullPath); os.IsNotExist(err) {
		if autoCreate {
			return l.MakeDir(l.fullPath)
		}
		l.errText = fmt.Sprintf("the path: %s is not exists", l.fullPath)
		return false
	}
	return true
}

// MakeDir make path directory
func (l *Local) MakeDir(path string) bool {
	err := os.MkdirAll(path, 0755)
	if err != nil {
		l.errText = err.Error()
		return false
	}
	return true
}

// Save file to path
func (l *Local) Save(file io.Reader) bool {
	if !l.CheckPath(true) {
		return false
	}
	out, err := os.Create(l.fullPath + l.fileName)
	if err != nil {
		l.errText = err.Error()
		return false
	}
	defer out.Close()
	_, err = io.Copy(out, file)
	if err != nil {
		l.errText = err.Error()
		return false
	}
	l.url = strings.TrimSuffix(l.Domain, "/") + "/" + l.fullPath + l.fileName
	return true
}

// Remove file
func (a *Local) Remove(file string) bool {
	_, err := os.Stat(file)
	if err != nil {
		a.errText = err.Error()
		return false
	}
	err = os.Remove(file)
	if err != nil {
		a.errText = err.Error()
		return false
	}
	return true
}
